package com.gexin.controller.system.user;
import java.util.Date;
import java.util.List;

import com.gexin.common.WebConst;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.MD5;
import com.gexin.common.utils.StringUtil;
import com.gexin.common.utils.WebUtils;
import com.gexin.core.web.SystemBaseController;
import com.gexin.model.system.AdminRole;
import com.gexin.model.system.AdminUser;
import com.gexin.model.system.AdminUserRole;
import com.gexin.model.system.RoleKit;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
/**
 * 管理员管理
 * @author 肖得明
 *  
 */
@ControllerBind(controllerKey = "/system/role/user", viewPath = "WEB-INF/system/admin/")
public class AdminUserController extends SystemBaseController {
	
	public void update_password(){
		render("admin_repass.html");
	}
	/**
	 * 密码修改
	 */
	public void update_pass(){
		Integer id = getLogintUser().getId();
		String resPassword = getPara("oldPassword");
		String password = getPara("password");
		String resPasswordMD5 = MD5.MD5EncodePass(resPassword);
		AdminUser user = AdminUser.dao.findFirst("select * from t_admin_user where id = ? and  password = ?",id,resPasswordMD5);
		if(user==null){
			fail("原密码错误");
			return ;
		}else{
			String passwordMD5 = MD5.MD5EncodePass(password);
			user.setPassword(passwordMD5);
			user.update();
			success("修改成功");
		}
	}
	
	//资料设置
	public void set(){
		setAttr("user", AdminUser.dao.findById(getLogintUser().getId()));
		render("admin_set.html");
	}
	//更新用户资料
	public void set_save(){
		AdminUser  user=  getModel(AdminUser.class,"user");
		user.setId(getLogintUser().getId());
		user.update();
		setSessionAttr(WebConst.Session_SysUser, AdminUser.dao.findById(getLogintUser().getId()));
		success();
	}
	//首页
	public void index(){
		AdminUser user   =  getModel(AdminUser.class,"admin");
		setAttr("admin", user);
		
		Page<AdminUser> userPage = AdminUser.dao.paginate(getpage(), WebConst.Page_Size,user);
		for (AdminUser obj:userPage.getList()) {
			obj.put("roleNames",AdminUserRole.dao.getRoleNames(obj.getId()));
		}
		paginate(userPage);
		//Subject subject = SecurityUtils.getSubject();
		if (isAjax()) {
			success(userPage);
		}else {
			render("admin_list.html");
		}
		
	}
	//添加或者修改账户信息
	public void add_edit(){
		setAttr("rolelist", AdminRole.dao.getAll());
		AdminUser user=  AdminUser.dao.findById(getPara(0));
		if (user!=null) {
			List<AdminUserRole> list =AdminUserRole.dao.getRoleIds(user.getId());
			if (list.size()>0) {
				setAttr("roleIds", listToArray(list));
				//System.err.println(JsonKit.toJson(listToArray(list)));
			}else {
				setAttr("roleIds","");
			}
		}else {
			setAttr("roleIds","");//防止页面beetl变量报未定义
		}
		
		setAttr("admin", user);
		render("admin_add.html");
	}
	
	//查看用户信息
	public void info(){
		
	}
	//保存数据
	public void save(){
		AdminUser admin = getModel(AdminUser.class,"admin");
		admin.setManagerChannelIds(StringUtil.array_ToStr(getParaValues("admin.manager_channel_ids")));
		String roles[] =  getParaValues("admin.role_id");
		//System.err.println(admin.getInt("usertype"));
		//判断状态
		if(admin.get("state")==null){
			admin.set("state", 1);	
		}
		if(StringUtil.show(admin.get("id")).equals("")){
			admin.set("createtime", new Date());
			admin.set("password", MD5.MD5EncodePass(admin.getStr("password")));
			//Tlogger.infor_Sys("新增用户："+admin.getStr("username"));
			admin.save();
		}else{
			RoleKit.clearUserRoleCache(admin.getId());
			admin.update();
		}
		AdminUserRole.dao.saveUserRole(admin.getId(), roles);
		redirect("/system/role/user/");
	}
	
	//检查用户名是否存在
	public void checkname(){
		if(AdminUser.dao.getAdminByUsername(getPara("value"))!=null){
			renderJson(new ApiResponse(true));
		}else{
			renderJson(new ApiResponse(false));
		}
	}
	
	//重置用户在密码 
	public void resetpass(){
		AdminUser.dao.findById(getParaToInt(0, 0)).set("password", MD5.MD5EncodePass("123456")).update();
		success();
	}
	
	//删除用户信息
	public void delete(){
		AdminUser.dao.deleteById(getParaToInt());
		Db.delete(" DELETE from t_admin_user_role WHERE user_id ="+getParaToInt());//删除权限组关联数据
		success();
	}
	//验证密码
	public void checkpwd(){
		String password =  getPara("password");
		if(password==null){
			renderJson(WebUtils.validata(false, "原始不能为空"));
			return ;
		}
		AdminUser admin = getSessionAttr(WebConst.Session_SysUser);
		if(admin==null){
			admin=getSessionAttr(WebConst.Session_SysUser);
		}
		admin = AdminUser.dao.getAdminByUsername(admin.getStr("username"));
		if(admin.getStr("password").equals(MD5.MD5EncodePass(password))){
			renderJson(WebUtils.validata(true, "密码验证成功！"));
		}else{
			renderJson(WebUtils.validata(false, "原始密码输入错误！"));
		}
	}
	
	
	public Integer[] listToArray(List<AdminUserRole> list) {
		  Integer[] array = new Integer[list.size()];
		  for (int i = 0; i < list.size(); i++) {
		      array[i] = list.get(i).getInt("role_id");
		  }
		  return array;
	}
	
	
	
}